package org.jeecg.modules.arc.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.arc.entity.ArcAccount;
import org.jeecg.modules.arc.entity.ArcAccountMeter;
import org.jeecg.modules.arc.entity.ArcContacts;
import org.jeecg.modules.arc.entity.ArcCustomers;
import org.jeecg.modules.arc.service.IArcAccountMeterService;
import org.jeecg.modules.arc.service.IArcAccountService;
import org.jeecg.modules.arc.service.IArcContactsService;
import org.jeecg.modules.arc.service.IArcCustomersService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

/**
 * @Description: 缴费账户关联水表用户
 * @Author: jeecg-boot
 * @Date:   2022-02-18
 * @Version: V1.0
 */
@Api(tags="缴费账户关联水表用户")
@RestController
@RequestMapping("/arc/arcAccountMeter")
@Slf4j
public class ArcAccountMeterController extends JeecgController<ArcAccountMeter, IArcAccountMeterService> {
	@Autowired
	private IArcAccountMeterService arcAccountMeterService;
	@Autowired
	private IArcCustomersService arcCustomersService;
	@Autowired
	private IArcContactsService arcContactsService;
	@Autowired
	private IArcAccountService arcAccountService;

	/**
	 * 分页列表查询
	 *
	 * @param arcAccountMeter
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	@AutoLog(value = "缴费账户关联水表用户-分页列表查询")
	@ApiOperation(value="缴费账户关联水表用户-分页列表查询", notes="缴费账户关联水表用户-分页列表查询")
	@GetMapping(value = "/list")
	public Result<?> queryPageList(ArcAccountMeter arcAccountMeter,
								   @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
								   @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
								   HttpServletRequest req) {
		arcAccountMeter.setDelFlag(0);
		QueryWrapper<ArcAccountMeter> queryWrapper = QueryGenerator.initQueryWrapper(arcAccountMeter, req.getParameterMap());
		Page<ArcAccountMeter> page = new Page<ArcAccountMeter>(pageNo, pageSize);
		IPage<ArcAccountMeter> pageList = arcAccountMeterService.page(page, queryWrapper);
		return Result.OK(pageList);
	}

	/**
	 *   添加
	 *
	 * @param arcAccountMeter
	 * @return
	 */
	@AutoLog(value = "缴费账户关联水表用户-添加")
	@ApiOperation(value="缴费账户关联水表用户-添加", notes="缴费账户关联水表用户-添加")
	@PostMapping(value = "/add")
	public Result<?> add(@RequestBody ArcAccountMeter arcAccountMeter) {

		if(oConvertUtils.isNotEmpty(arcAccountMeter.getCusId())){

			int count = arcAccountMeterService.count(new LambdaQueryWrapper<ArcAccountMeter>()
					.in(ArcAccountMeter::getCusId, arcAccountMeter.getCusId())
					.eq(ArcAccountMeter::getAccountId,arcAccountMeter.getAccountId())
					.eq(ArcAccountMeter::getDelFlag,0));
			if(count>0){
				return Result.error("选择的水表用户在该缴费账户已存在！");
			}

			ArcAccountMeter meters = new ArcAccountMeter();
			BeanUtils.copyProperties(arcAccountMeter,meters);

			String cusId = arcAccountMeter.getCusId();
			if(oConvertUtils.isNotEmpty(cusId)){
				List<ArcCustomers> list = arcCustomersService.list(new LambdaQueryWrapper<ArcCustomers>()
						.eq(ArcCustomers::getCode, cusId)
						.eq(ArcCustomers::getDelFlag, 0));
				if(null != list && list.size()>0){
					ArcCustomers arcCustomers = list.get(0);
					meters.setCusName(arcCustomers.getCusName());
				}else{
					return Result.error("水表用户不存在！");
				}
			}

			//String[] cusNames = arcAccountMeter.getCusName().split(",");
			//for (int i = 0; i < cusIds.length; i++) {

				meters.setCusId(cusId);

				arcAccountMeterService.save(meters);

				//逻辑删除被绑的账号水表：被绑水表cusId,不是当前绑定的缴费账号
				arcAccountMeterService.update(new LambdaUpdateWrapper<ArcAccountMeter>()
						.set(ArcAccountMeter::getDelFlag,1)
						.eq(ArcAccountMeter::getCusId,cusId)
						.ne(ArcAccountMeter::getAccountId,arcAccountMeter.getAccountId())
				);

			//更新用户档案的统一缴费账户
			ArcAccount arcAccount = arcAccountService.getById(arcAccountMeter.getAccountId());

			arcContactsService.update(new LambdaUpdateWrapper<ArcContacts>().set(ArcContacts::getCode,arcAccount.getCode())
					.eq(ArcContacts::getCode,cusId));

			return Result.OK("添加成功！");
		}
		return Result.OK("添加成功！");
	}

	/**
	 *  编辑
	 *
	 * @param arcAccountMeter
	 * @return
	 */
	@AutoLog(value = "缴费账户关联水表用户-编辑")
	@ApiOperation(value="缴费账户关联水表用户-编辑", notes="缴费账户关联水表用户-编辑")
	@PutMapping(value = "/edit")
	public Result<?> edit(@RequestBody ArcAccountMeter arcAccountMeter) {
		if(oConvertUtils.isNotEmpty(arcAccountMeter.getCusId())){
			String cusIds = arcAccountMeter.getCusId();

			boolean remove = arcAccountMeterService.remove(new LambdaQueryWrapper<ArcAccountMeter>()
					.eq(ArcAccountMeter::getCusId, cusIds)
					.eq(ArcAccountMeter::getAccountId, arcAccountMeter.getAccountId())
					.eq(ArcAccountMeter::getDelFlag, 0));
			//先删除 再增加
			System.out.println(remove);

			int count = arcAccountMeterService.count(new LambdaQueryWrapper<ArcAccountMeter>()
					.in(ArcAccountMeter::getCusId, arcAccountMeter.getCusId())
					.eq(ArcAccountMeter::getAccountId,arcAccountMeter.getAccountId())
					.eq(ArcAccountMeter::getDelFlag,0));
			if(count>0){
				return Result.error("选择的水表用户在该缴费账户已存在！");
			}

			ArcAccountMeter meters = new ArcAccountMeter();
			BeanUtils.copyProperties(arcAccountMeter,meters);

			String cusId = arcAccountMeter.getCusId();
			if(oConvertUtils.isNotEmpty(cusId)){
				List<ArcCustomers> list = arcCustomersService.list(new LambdaQueryWrapper<ArcCustomers>()
						.eq(ArcCustomers::getCode, cusId)
						.eq(ArcCustomers::getDelFlag, 0));
				if(null != list && list.size()>0){
					ArcCustomers arcCustomers = list.get(0);
					meters.setCusName(arcCustomers.getCusName());
				}else{
					return Result.error("水表用户不存在！");
				}
			}
			meters.setCusId(cusId);
			arcAccountMeterService.updateById(meters);

			//更新用户档案的统一缴费账户
			ArcAccount arcAccount = arcAccountService.getById(arcAccountMeter.getAccountId());

			arcContactsService.update(new LambdaUpdateWrapper<ArcContacts>().set(ArcContacts::getCode,arcAccount.getCode())
					.eq(ArcContacts::getCode,cusId));

			return Result.OK("编辑成功!");
		}

		return Result.OK("编辑异常!");
	}

	/**
	 *   通过id删除
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "缴费账户关联水表用户-通过id删除")
	@ApiOperation(value="缴费账户关联水表用户-通过id删除", notes="缴费账户关联水表用户-通过id删除")
	@DeleteMapping(value = "/delete")
	public Result<?> delete(@RequestParam(name="id",required=true) String id) {
		ArcAccountMeter arcAccountMeter = arcAccountMeterService.getById(id);
		if(arcAccountMeter==null) {
			return Result.error("未找到对应数据");
		}


		//删除关联，更新用户档案的为自己的缴费账户

		List<ArcAccount> list = arcAccountService.list(new QueryWrapper<ArcAccount>().lambda()
				.eq(ArcAccount::getCode, arcAccountMeter.getCusId()));
		if(null != list && list.size()>0){
			ArcAccount arcAccount =list.get(0);
			arcContactsService.update(new LambdaUpdateWrapper<ArcContacts>()
					.set(ArcContacts::getCode,arcAccountMeter.getCusId())
				.eq(ArcContacts::getId,arcAccount.getContactId()));

			arcAccountMeter.setDelFlag(0);
			arcAccountMeter.setAccountId(arcAccount.getId());
			arcAccountMeterService.updateById(arcAccountMeter);

		}else{
			return Result.error("删除异常!");
		}

//		ArcAccount arcAccount = arcAccountService.list();
//		arcContactsService.update(new LambdaUpdateWrapper<ArcContacts>().set(ArcContacts::getCode,arcAccountMeter.getCusId())
//				.eq(ArcContacts::getCode,arcAccount.getCode())
//		);

		return Result.OK("删除成功!");
	}

	///**
	// *  批量删除
	// *
	// * @param ids
	// * @return
	// */
	//@AutoLog(value = "缴费账户关联水表用户-批量删除")
	//@ApiOperation(value="缴费账户关联水表用户-批量删除", notes="缴费账户关联水表用户-批量删除")
	//@DeleteMapping(value = "/deleteBatch")
	//public Result<?> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
	//	boolean update = arcAccountMeterService.update(new LambdaUpdateWrapper<ArcAccountMeter>()
	//			.set(ArcAccountMeter::getDelFlag, 1)
	//			.in(ArcAccountMeter::getId, Arrays.asList(ids.split(","))));
	//	if(update) {
	//		return Result.OK("批量删除成功!");
	//	}else{
	//		return Result.OK("批量删除异常!");
	//	}
	//}

	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "缴费账户关联水表用户-通过id查询")
	@ApiOperation(value="缴费账户关联水表用户-通过id查询", notes="缴费账户关联水表用户-通过id查询")
	@GetMapping(value = "/queryById")
	public Result<?> queryById(@RequestParam(name="id",required=true) String id) {
		ArcAccountMeter arcAccountMeter = arcAccountMeterService.getById(id);
		if(arcAccountMeter==null) {
			return Result.error("未找到对应数据");
		}
		return Result.OK(arcAccountMeter);
	}

    /**
    * 导出excel
    *
    * @param request
    * @param arcAccountMeter
    */
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, ArcAccountMeter arcAccountMeter) {
        return super.exportXls(request, arcAccountMeter, ArcAccountMeter.class, "缴费账户关联水表用户");
    }

    /**
      * 通过excel导入数据
    *
    * @param request
    * @param response
    * @return
    */
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, ArcAccountMeter.class);
    }

}
